<?php

namespace app\task\command;

use app\admin\model\order\Mobile as MobileOrder;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 充值失败订单自动退款.
 */
class AutoRefund extends Command
{
    /**
     * 配置指令[每分钟跑1次].
     * 
     * sudo -u www php /www/wwwroot/api/think mobile:autoRefund
     */
    protected function configure()
    {
        $this->setName('mobile:autoRefund')
            ->setDescription('mobile order auto refund');
    }

    /**
     * 执行指令.
     *
     * sudo -u www php /www/wwwroot/api/think mobile:autoRefund
     *
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $start = date('Y-m-d H:I:s');
        echo '话费充值失败订单自动退款--' . PHP_EOL;
        $lockKey = 'mobile_order_auto_refund_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 1200);

        $list = Db::name('mobile_order')
            ->field('id')
            ->where('supplier_status', 4)
            ->where('refund_status', 2)
            ->limit(100)
            ->select()
            ->toArray();

        $done = 0;
        $model = new MobileOrder();
        foreach ($list as $order) {
            $res = $model->refund($order['id']);
            if (false === $res) {
                echo $order['id'] . '--' . $model->getError() . PHP_EOL;
            } else {
                ++$done;
            }
        }

        cache($lockKey, null);

        echo '话费订单充值失败自动退款：成功退 ' . $done . ' 单 ' . $start . '--' . date('Y-m-d H:i:s') . PHP_EOL;
    }
}
